package vip.gadfly.tiktok.core.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String executeHttpPost(String url, List<Map<String, String>> params)
            throws Exception {
        logger.info("executeHttpPost请求，入参url={}, params={}",url, JSON.toJSONString(params));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            UrlEncodedFormEntity urlEncodedFormEntity = getUrlEncodedFormEntity(params);
            if (urlEncodedFormEntity != null) {
                httpPost.setEntity(urlEncodedFormEntity);
            }

            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpPost.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        logger.info("executeHttpPost请求，返回结果result={}",result);
        return result;
    }

    public static String executeJsonParamHttpPost(String url, String textMsg) throws Exception {
        logger.info("executeJsonParamHttpPost请求，入参url={}, textMsg={}",url, textMsg);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(textMsg, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpPost.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        logger.info("executeJsonParamHttpPost请求，返回结果result={}",result);
        return result;
    }



    public static String executeHttpDelete(String url)
            throws Exception {
        logger.info("executeHttpPost请求，入参url={}, params={}",url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            HttpDelete delete = new HttpDelete(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(30000).build();
            delete.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(delete);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                delete.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        logger.info("executeHttpDelete，返回结果result={}",result);
        return result;
    }
    public static String executeHttpGet(String url)
            throws IOException {
        logger.info("executeHttpGet请求，入参url={}",url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {

            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(30000).build();
            httpGet.setConfig(requestConfig);
            CloseableHttpResponse response = httpclient.execute(httpGet);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpGet.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        logger.info("executeHttpGet请求，返回结果result={}",result);
        return result;
    }

    private static UrlEncodedFormEntity getUrlEncodedFormEntity(List<Map<String, String>> params) {
        ArrayList formparams = new ArrayList();
        if (params != null && params.size() > 0) {
            for (int entity = 0; entity < params.size(); ++entity) {
                Iterator var4 = ((Map) params.get(entity)).keySet().iterator();

                while (var4.hasNext()) {
                    String key = (String) var4.next();
                    if (params.get(entity).get(key) != null)
                        formparams.add(new BasicNameValuePair(key, ((Map) params.get(entity)).get(key).toString()));
                    // formparams.add(new BasicNameValuePair(key, value))
                }
            }
        }
        if (formparams.size() > 0) {
            UrlEncodedFormEntity var6 = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            return var6;
        }
        return null;
    }

    public static void getDownloadFile(String url, String jsonStr, String destFileName)
            throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httppost = new HttpGet(url);
        CloseableHttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        File file = new File(destFileName);

        try {
            FileOutputStream fout = new FileOutputStream(file);
            byte[] tmp = new byte[1024];

            while (true) {
                int l1;
                if ((l1 = in.read(tmp)) == -1) {
                    fout.flush();
                    fout.close();
                    break;
                }

                fout.write(tmp, 0, l1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            in.close();
        }

        httpclient.close();
    }

    public static String executeHeaderHttpPost(String url, List<Map<String, String>> params,String token)
            throws Exception {
        logger.info("executeHttpPost请求，入参url={}, params={}",url, JSON.toJSONString(params));
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            if(StringUtils.isNotBlank(token)){
                httpPost.setHeader("token",token);
            }
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            UrlEncodedFormEntity urlEncodedFormEntity = getUrlEncodedFormEntity(params);
            if (urlEncodedFormEntity != null) {
                httpPost.setEntity(urlEncodedFormEntity);
            }

            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpPost.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        logger.info("executeHttpPost请求，返回结果result={}",result);
        return result;
    }

    public static String executeHeaderJsonParamHttpPost(String url, String textMsg,String token) throws Exception {
        logger.info("executeJsonParamHttpPost请求，入参url={}, textMsg={}",url, textMsg);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = null;

        try {
            HttpPost httpPost = new HttpPost(url);
            if(StringUtils.isNotBlank(token)){
                httpPost.setHeader("token",token);
            }
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                    .setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(textMsg, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);

            try {
                result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                httpPost.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        logger.info("executeJsonParamHttpPost请求，返回结果result={}",result);
        return result;
    }

    private static final int TIMEOUT = 6000;
    private static final int BUFFER = 5120;

    public static String invokeHttp(String httpUrl){
        return invokeHttp(httpUrl, 6000);
    }

    public static String invokeHttp(String httpUrl, int timeout){
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try{
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            conn.setDoOutput(true);
            OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "ISO8859-1");
            os.flush();
            conn.connect();
            if(conn.getResponseCode() == 200){
                InputStream is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String buffer = null;
                while((buffer = br.readLine()) != null){
                    if(StringUtils.isNotEmpty(buffer)){
                        result.append(buffer);
                    }
                }
                if(br != null){
                    br.close();
                }
                if(is != null){
                    is.close();
                }
            }
            if(os != null)
                os.close();
        }catch(ConnectException e){
            System.out.println(httpUrl + " not connectable");
        }catch(IOException e){
            System.out.println(httpUrl + " not connectable");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(conn != null){
                conn.disconnect();
                conn = null;
            }
        }
        return result.toString();
    }




    public static void main(String[] args) throws Exception {

    }
}
